package net.huashitong.service.money;

import net.huashitong.entity.WeChatPayRequestModel;
import net.huashitong.ssydt.money.constant.MoneyConsts;
import net.huashitong.ssydt.money.entity.SsMoneyOrder;
import net.huashitong.ssydt.provider.utils.date.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;

;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.16
 */
@Service
@Transactional
public class WeChatPaySuccessServiceImpl implements WeChatPaySuccessService {

    private Logger logger = LoggerFactory.getLogger(WeChatPaySuccessServiceImpl.class);

    private SsMoneyOrderService ssMoneyOrderService;

    private MoneyService moneyService;

    @Autowired
    public WeChatPaySuccessServiceImpl(SsMoneyOrderService ssMoneyOrderService,
                                       MoneyService moneyService) {
        this.ssMoneyOrderService = ssMoneyOrderService;
        this.moneyService = moneyService;
    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public void paySuccess(WeChatPayRequestModel model) {
        SsMoneyOrder ssMoneyOrder = this.ssMoneyOrderService.getByOrderId(model.getOut_trade_no());
        if (ssMoneyOrder == null) {
            logger.info("微信订单号 [{}] 支付金额 (单位分)[{}] 商户订单号 [{}] ,在系统中不存在",
                    model.getTransaction_id(), model.getTotal_fee(), model.getOut_trade_no());
            return;
        }
        //防止重复处理订单
        if (MoneyConsts.OrderState.PAID.equals(ssMoneyOrder.getOrderState())) {
            return;
        }
        ssMoneyOrder.setPayType(MoneyConsts.PayType.WE_CHAT_PAY);
        ssMoneyOrder.setPayAccount(model.getOpenid());
        ssMoneyOrder.setPayOrderId(model.getTransaction_id());
        ssMoneyOrder.setGmtPay(this.getGmtPay(model.getTime_end()));
        ssMoneyOrder.setOrderState(MoneyConsts.OrderState.PAID);
        ssMoneyOrderService.update(ssMoneyOrder);
        moneyService.payCallback(ssMoneyOrder);//支付回调
    }


    /**
     * 格式化时间
     *
     * @param str
     * @return
     */
    private Date getGmtPay(String str) {
        try {
            return DateUtils.parseDate(str, "yyyyMMddHHmmss");
        } catch (ParseException e) {
            return null;
        }
    }
}
